#include "powertray.h"
#include <QDBusReply>
#include <QProcess>
#include <QDebug>
PowerTray::PowerTray(QObject *parent):QObject(parent){
    upowerInterface = new QDBusInterface("org.freedesktop.UPower",
                                         "/org/freedesktop/UPower",
                                         "org.freedesktop.UPower",
                                         QDBusConnection::systemBus(),this);
    QDBusReply<QList<QDBusObjectPath>> devicesreply = upowerInterface->call("EnumerateDevices");
    if(devicesreply.isValid()){
        for(const QDBusObjectPath &path : devicesreply.value()){//遍历设备路径
            QDBusInterface device("org.freedesktop.UPower",
                                  path.path(),
                                  "org.freedesktop.DBus.Properties",//属性接口
                                  QDBusConnection::systemBus(),this);
            QDBusReply<QVariant> typeReply = device.call("Get",
                                                         "org.freedesktop.UPower.Device",
                                                         "Type");

            if(typeReply.isValid()&&typeReply.value().toUInt()==2){//2表示电池设备
                batteryInterface = new QDBusInterface("org.freedesktop.UPower",
                                                      path.path(),
                                                      "org.freedesktop.UPower.Device",
                                                      QDBusConnection::systemBus(),this);
                batteryExists = true;
                qDebug()<<"batteryExits : 找到电池了吗"<<batteryExists;
                //监听DBus,电池相关信息的变化
                QDBusConnection::systemBus().connect("org.freedesktop.UPower",
                                                     path.path(),
                                                     "org.freedesktop.DBus.Properties",
                                                     "PropertiesChanged",this,
                                                     SLOT(onBatteryPropertiesChanged(QString,QVariantMap,QStringList)));
                break;
            }
        }
    }else{
        qDebug()<<"devicesreply 无效"<<devicesreply.error();
    }
    qDebug()<<"batteryExits: "<<batteryExists;
    trayIcon = new QSystemTrayIcon(this);
    trayMenu = new QMenu();
    //创建更新定时器
    updateTimer = new QTimer(this);
    //初始设置
    setupTrayIcon();
    //创建托盘菜单
    creatTrayMenu();
    connect(trayIcon,&QSystemTrayIcon::activated,this,&PowerTray::onTrayIconActivated);
    connect(updateTimer,&QTimer::timeout,this,&PowerTray::updateBatteryStatus);

   //updateTimer->start(30000);
}
PowerTray::~PowerTray(){
    trayIcon->hide();
}
void PowerTray::setVisible(bool visible){
    qDebug()<<"visible:  "<<visible;
    if(visible){
        updateBatteryStatus();
        updateTimer->start(30000);
        trayIcon->show();
    }else{
        trayIcon->hide();
        updateTimer->stop();
    }
}
void PowerTray :: creatTrayMenu(){
    trayMenu->clear();
    QAction *batteryInfo = new QAction(this);
    batteryInfo->setEnabled(false);
    trayMenu->addAction(batteryInfo);
    trayMenu->addSeparator();

    QAction *powerSettings = new QAction(tr("Power Setting"),this);

    connect(powerSettings,&QAction::triggered,this,&PowerTray::onShowSettings);
    trayMenu->addAction(powerSettings);
    trayMenu->addSeparator();
    //退出菜单
    QAction *exitAction = new QAction(tr("exit"),this);

    connect(exitAction,&QAction::triggered,this,&PowerTray::onExit);
    trayMenu->addAction(exitAction);
    trayIcon->setContextMenu(trayMenu);
}
void PowerTray::setupTrayIcon(){
    trayIcon->setIcon(QIcon::fromTheme("battery-full"));
    updateBatteryStatus();
}
bool  PowerTray::isVisible() const{
    return trayIcon->isVisible();
}
void PowerTray::updateBatteryStatus(){
    if(!checkBatteryExists()){
        //trayIcon->setIcon(QIcon::fromTheme("ac-adapter"));
        trayIcon->setToolTip(tr("No battery detected"));
        return;
    }
    int capacity = getBatteryCapacity();
    qDebug()<<"更新电量"<<capacity;
    QString status = getBatteryStatus();
    qDebug()<<"更新电池状态"<<status;
    QString iconName = getBatteryIconName(capacity,status);
    trayIcon->setIcon(QIcon::fromTheme(iconName));
    qDebug()<<"iconName: "<<iconName;
    QString toolTip;
    if(status == "Fully charged"){
           toolTip = tr("Fully charged (100%)");
     }
    else if(status == "Charging"){
        toolTip = tr("%1% charging").arg(capacity);
    }else{
        toolTip = tr("%1% remaining").arg(capacity);
    }
    trayIcon->setToolTip(toolTip);
    if(trayMenu && trayMenu->actions().size()>0){
        QAction *batteryAction = trayMenu->actions().first();
        batteryAction->setText(tr("Battery %1% (%2)").arg(capacity).arg(status));
    }
}
void PowerTray::onBatteryPropertiesChanged(QString interface, QVariantMap changedProps, QStringList invalidatedProps){

    if(interface!="org.freedesktop.UPower.Device") return;
    if(changedProps.contains("Percentage")||changedProps.contains("State")){
        updateBatteryStatus();
    }

}
bool PowerTray::checkBatteryExists(){
    return batteryExists;
}
QString PowerTray::getBatteryIconName(int percentage, const QString &status){
    if(status == "Charging"){
        if(percentage>=90) return "battery-full-charging";
        if (percentage >= 70) return "battery-good-charging";
        if (percentage >= 40) return "battery-medium-charging";
        return "battery-low-charging";
    }else{
        if (percentage >= 90) return "battery-full";
        if (percentage >= 70) return "battery-good";
        if (percentage >= 40) return "battery-medium";
        return "battery-low";
    }
}
QString PowerTray:: getBatteryStatus(){
    if(!batteryInterface) return "Unknown";
    QVariant reply = batteryInterface->property("State");
    qDebug()<<"输出电池状态"<<reply;
    if(!reply.isValid()) {
        qDebug()<<"state 无效";
        return "Unknown";
    }
    switch(reply.toUInt()){
    case 1:return "Charging";
    case 2:return "DisCharging";
    case 3:return "Empty";
    case 4:return "Fully charged";
    default:return "Unknown";
    }
}
int PowerTray::getBatteryCapacity() const{
    if(!batteryInterface) return 100;
    QVariant reply = batteryInterface->property("Percentage");
    if(reply.isValid()){
        return qRound(reply.toDouble());
    }
    else {
        qDebug()<<"电量 无效"<<reply;
    }

}
void PowerTray::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason){
    if(reason==QSystemTrayIcon::DoubleClick){
        emit showSettingsRequested();
    }
}
void PowerTray::onShowSettings(){
    emit showSettingsRequested();
}
void PowerTray::onExit(){
    emit exitRequired();
}

















